package com.wwj.gateway.filter;

import com.wwj.common.constant.CommonCodeEnum;
import com.wwj.common.constant.CommonConstant;
import com.wwj.common.utils.TokenCheck;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Resource
    private NotAuthUrlProperties notAuthUrlProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String currentPath = exchange.getRequest().getURI().getPath();
        if (shouldSkip(currentPath)) {
            log.info("==========跳过URL:{}==========",currentPath);
            return chain.filter(exchange);
        }
        log.info("==========进入网关鉴权认证==========");
        if(!TokenCheck.checkToken(exchange.getRequest().getHeaders().getFirst(CommonConstant.REQUEST_HEADER_TOKEN))) {
            log.info("==========认证失败==========");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);  // 401
            return exchange.getResponse().setComplete();
        }else {
            log.info("==========认证成功==========");
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private boolean shouldSkip(String currentUrl) {
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String skipPath : notAuthUrlProperties.getShouldSkipUrls()) {
            if (pathMatcher.match(skipPath, currentUrl)) {
                return true;
            }
        }
        return false;
    }
}
